package com.sugon.controller.device;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.DataFilter;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.DevAmPlanEntity;
import com.sugon.entity.DevAmRulesEntity;
import com.sugon.entity.DeviceInfoEntity;
import com.sugon.modules.base.model.vo.BaseApproveParamVO;
import com.sugon.modules.base.model.vo.ProcessProgressConst;
import com.sugon.modules.device.model.vo.SaveDevAmRuleParam;
import com.sugon.modules.device.service.IDeviceAmRulesManager;
import com.sugon.service.DevAmPlanService;
import com.sugon.service.DevAmRulesService;
import com.sugon.service.DeviceInfoService;
import com.sugon.service.SysConfigService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

/**
 * 自主维护规程管理Controller
 *
 * @author YUXD
 * @date 2023-01-23
 */
@Controller
@RequestMapping("devammaintenancerules")
public class DevAmRulesController {
    @Resource
    private DevAmRulesService devAmRulesService;
    @Resource
    private DevAmPlanService devAmPlanService;
    @Resource
    private IDeviceAmRulesManager deviceAmRulesManager;
    @Resource
    private SysConfigService configService;
    @Resource
    private DeviceInfoService deviceInfoService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @ResponseBody
    @DataFilter(deptAlias = "DEPT_CODE", userAlias = "ORG_USER_ID")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<DevAmRulesEntity> devMaintenPlanList = devAmRulesService.queryList(query);
        int total = devAmRulesService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(devMaintenPlanList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        DevAmRulesEntity devMaintenPlan = devAmRulesService.queryObject(id);

        return R.ok().put("devMaintenPlan", devMaintenPlan);
    }

    /**
     * 保存
     */
    @NonBusinessParamValid
    @RequestMapping("/save")
    @ResponseBody
    public R save(@Validated @RequestBody SaveDevAmRuleParam rulesParam, BindingResult bindingResult) {
        // 校验设备是否存在
        String devId = rulesParam.getDevId();
        DeviceInfoEntity device = deviceInfoService.queryObject(devId);
        if (device == null) {
            return R.error("设备不存在，请确认！");
        }
        rulesParam.setDevName(device.getDevName());
        rulesParam.setDevSupply(device.getDevSupply());
        rulesParam.setDevTypeS(device.getDevTypeS());
        return deviceAmRulesManager.createDeviceAmMaintenanceRules(rulesParam) ? R.ok() : R.error();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody DevAmRulesEntity devMaintenPlan) {
        devAmRulesService.update(devMaintenPlan);

        return R.ok();
    }

    /**
     * 自主维护规程由车间的生产管理室主任审核
     */
    @NonBusinessParamValid
    @RequestMapping("/check")
//    @RequiresPermissions("devAmRule:approve")
    @ResponseBody
    public R check(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        return deviceAmRulesManager.workshopBatchApprove(approveParam) ? R.ok() : R.error();
    }

    /**
     * 删除- 逻辑
     */
    @RequestMapping("/updateDel")
    @RequiresPermissions("devAmRule:delete")
    @ResponseBody
    public R updateDel(@RequestBody DevAmRulesEntity devMaintenPlan) {
        devAmRulesService.update(devMaintenPlan);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("devAmRule:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        devAmRulesService.deleteBatch(ids);
        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<DevAmRulesEntity> list = devAmRulesService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 罗列出当前车间产线下已审核通过的设备自主维护规程
     *
     * @param params
     * @return
     */
    @RequestMapping("/listByEnd")
    @ResponseBody
    @DataFilter(deptAlias = "DI.DEPT_CODE", userAlias = "ORG_USER_ID")
    public R listByEnd(@RequestParam Map<String, Object> params) {
        // 检查参数中是否含有计划ID,如果有找到设备
        String planId = MapUtil.getStr(params, "planId");
        if (StrUtil.isEmpty(planId)) {
            return R.error("设备维护计划必选！");
        }
        // 校验设备维护计划是否存在
        DevAmPlanEntity devMaintenancePlan = devAmPlanService.queryObject(planId);
        if (devMaintenancePlan == null) {
            return R.error("设备维护计划不存在，请确认！");
        }
        // 列出产线下已通过审核且有效的设备规程列表
        params.put("devLineId", devMaintenancePlan.getDevLineId());
        params.put("progress", ProcessProgressConst.PASSED);
        params.put("isValid", 1);
        Query query = new Query(params);
        List<DevAmRulesEntity> devMaintenPlanList = devAmRulesService.queryList(query);
        int total = devAmRulesService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(devMaintenPlanList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 导入Excel
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/imports")
    @ResponseBody
    public R imports(@RequestParam("file") MultipartFile file) {
        return R.ok().put("err", devAmRulesService.imports2(file));
    }

    @RequestMapping("/exportData")
    public void export(@RequestParam Map<String, Object> params, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        // 移除空值参数
        com.sugon.utils.MapUtil.removeEmptyValue(params);
        TemplateExportParams templateExportParams = new TemplateExportParams(configService.getPoiTemplatePath() + "devMaintenanceDirectiveRulesTemplate.xlsx");
        modelMap.put(TemplateExcelConstants.FILE_NAME, "设备维护规程导出_" + com.sugon.modules.utils.DateUtil.today());
        modelMap.put(TemplateExcelConstants.PARAMS, templateExportParams);
        modelMap.put(TemplateExcelConstants.MAP_DATA, devAmRulesService.prepareExportData(params));
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

}
